package bookManage.Controller.servlet;

import bookManage.Model.entity.Book;
import bookManage.Model.service.ServiceImpl;
import bookManage.utils.DBUtil;
import bookManage.utils.JsonUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

/**
 * @BelongsProject: library-management-system-master
 * @BelongsPackage: bookManage.Controller
 * @Author: yuan wang
 * @CreateTime: 2023-02-02  15:31
 * @Description: 编辑书籍的Servlet，用于展示书籍修改之前的数据，以便于管理员在原有基础上进行便捷修改
 * @Version: 1.0
 */
@WebServlet(name = "EditBookStart", value = "/manager/BookShow/BookContent/EditBookStart")
public class EditBookStart extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String jsonString = String.valueOf(JsonUtil.getJson(req));
        JSONObject jsonObject = JSON.parseObject(jsonString);

        ServiceImpl service = new ServiceImpl();

        String number = jsonObject.getString("number");

        PrintWriter out = resp.getWriter();
        JSONObject object = new JSONObject();

        try {
            Book book = service.queryBookContent(number);
            if (book != null) {
                object.put("code", "200");
                object.put("bookName", book.getBookName());
                object.put("writer", book.getWriter());
                object.put("kind", book.getKind());
                object.put("number", book.getNumber());
                object.put("publish", book.getPublish());
                object.put("bookIntroduction", book.getBookIntroduction());
                object.put("writerIntroduction", book.getWriterIntroduction());
                object.put("picture", book.getPicture());
                out.println(object);
            } else {
                object.put("code", "-1");
                object.put("message", "无法对此书进行编辑");
                out.println(object);
            }
        } catch (SQLException e) {
            object.put("code", "-1");
            object.put("message", "无法对此书进行编辑");
            out.println(object);
        } finally {
            try {
                DBUtil.freeConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        doGet(req, resp);
    }
}
